/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkAssignStmt, ArkClass, ArkField, ArkFile, ArkInstanceFieldRef, ArkMethod, ArkNewExpr, ArkStaticFieldRef, ClassSignature, ClassType, Constant, DEFAULT_ARK_CLASS_NAME, ImportInfo, Local, Stmt, Value } from 'arkanalyzer/lib';
import { BaseChecker, BaseMetaData } from '../BaseChecker';

import { Rule, Defects, MethodMatcher, MatcherTypes, MatcherCallback, CheckerUtils, CheckerStorage } from '../../Index';
import { IssueReport } from '../../model/Defects';
import { VarInfo } from '../../model/VarInfo';
import { Scope as ModelScope } from '../../model/Scope';
import { NumberUtils } from '../../utils/checker/NumberUtils';

// 类型定义
interface StmtWithScope extends Stmt {
    scope?: {
        defList?: Array<{
            getName(): string;
            defStmt: Stmt;
        }>;
    };
}

// 常量定义
const HIGH_FRAME_RATE_THRESHOLD = 120;
const SPECIAL_FIELD_NAME = 'expectedFrameRateRange';
const MAX_RECURSION_DEPTH = 10;

const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: 'docs/no-high-loaded-frame-rate-range.md',
    description: `Avoid setting the expected, min, and max values of ExpectedFrameRateRange all to ${HIGH_FRAME_RATE_THRESHOLD} or higher.`,
    supportedFileExtensions: ['.ts', '.ets', '.js']
};
const TARGET_METHOD_SIGNATURES = [
    '@ohosSdk/api/@ohos.graphics.displaySync.d.ts: displaySync.DisplaySync.setExpectedFrameRateRange(ExpectedFrameRateRange)',
    '@ohosSdk/api/@ohos.graphics.displaySync.d.ts: displaySync.DisplaySync.setExpectedFrameRateRange(@ohosSdk/component/common.d.ts: ExpectedFrameRateRange)',
    `@ohosSdk/component/common.d.ts: ${DEFAULT_ARK_CLASS_NAME}.animateTo(@ohosSdk/component/common.d.ts: AnimateParam, @ohosSdk/component/common.d.ts: ${DEFAULT_ARK_CLASS_NAME}.%AM0())`,
    '@ohosSdk/api/@ohos.arkui.UIContext.d.ts: DynamicSyncScene.setFrameRateRange(ExpectedFrameRateRange)',
    '@ohosSdk/api/@ohos.arkui.UIContext.d.ts: DynamicSyncScene.setFrameRateRange(@ohosSdk/component/common.d.ts: ExpectedFrameRateRange)'
];

export class NoHighLoadedFrameRateRangeCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    /**
     * 获取帧率相关字段（固定为 expected、min、max）
     */
    private getFrameRateFields(fields: ArkField[]): string[] {
        const frameRateFields = ['expected', 'min', 'max'];
        return fields
            .map(f => f.getName())
            .filter(name => frameRateFields.includes(name));
    }

    private methodMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD
    };

    public registerMatchers(): MatcherCallback[] {
        const matchMethodCb: MatcherCallback = {
            matcher: this.methodMatcher,
            callback: this.check
        };
        return [matchMethodCb];
    }

    private arkFile: ArkFile;

    public check = (arkMethod: ArkMethod): void => {
        this.arkFile = arkMethod.getDeclaringArkFile();
        const originPath = this.arkFile.getName();
        if (!this.isSupportedFile(originPath)) {
            return;
        }
        const stmts = arkMethod.getBody()?.getCfg().getStmts();
        if (!stmts) {
            return;
        }

        for (const stmt of stmts) {
            this.processStatement(stmt, arkMethod);
        }
    };

    private processStatement(stmt: Stmt, arkMethod: ArkMethod): void {
        const invoke = CheckerUtils.getInvokeExprFromStmt(stmt);
        if (!invoke) {
            return;
        }

        if (!this.isTargetMethodSignature(invoke.getMethodSignature().toString())) {
            return;
        }

        // 检查第一个参数（ExpectedFrameRateRange 参数）
        const arg = invoke.getArg(0);

        const fieldValues = this.extractFieldValues(stmt, arg, arkMethod);
        if (this.isHighLoadedFrameRate(fieldValues)) {
            const methodName = invoke.getMethodSignature().getMethodSubSignature().getMethodName();
            this.reportIssue(arkMethod.getDeclaringArkFile(), stmt, methodName);
        }
    }

    /**
     * 检查是否为高负载帧率配置
     */
    private isHighLoadedFrameRate(fieldValues: number[]): boolean {
        return fieldValues.length === 3 &&
            fieldValues.every(value => Number.isFinite(value) && value >= HIGH_FRAME_RATE_THRESHOLD);
    }

    private isTargetMethodSignature(methodSignature: string): boolean {
        return TARGET_METHOD_SIGNATURES.includes(methodSignature);
    }

    /**
     * 提取字段值，支持多种参数类型
     */
    private extractFieldValues(stmt: Stmt, arg: Value, arkMethod: ArkMethod): number[] {
        if (arg instanceof Local) {
            const declaringStmt = arg.getDeclaringStmt();
            if (declaringStmt instanceof ArkAssignStmt) {
                const rightOp = declaringStmt.getRightOp();
                if (rightOp instanceof ArkNewExpr) {
                    return this.extractFromObjectLiteral(stmt, rightOp, arkMethod);
                }
            }
            return this.getFieldNum(stmt, arg, arg.getName());
        }

        if (arg instanceof ArkNewExpr) {
            return this.extractFromObjectLiteral(stmt, arg, arkMethod);
        }

        if (arg instanceof ArkInstanceFieldRef || arg instanceof ArkStaticFieldRef) {
            return this.extractFromFieldRef(stmt, arg, arkMethod);
        }

        return [];
    }

    /**
     * 从对象字面量中提取字段值
     */
    private extractFromObjectLiteral(stmt: Stmt, newExpr: ArkNewExpr, arkMethod: ArkMethod): number[] {
        const arkFile = arkMethod.getDeclaringArkFile();
        const fields = this.getObjectFields(newExpr, arkFile);
        if (!fields) {
            return [];
        }
        const result: number[] = [];
        const frameRateFields = this.getFrameRateFields(fields);

        for (const field of fields) {
            const fieldName = field.getName();

            if (fieldName === SPECIAL_FIELD_NAME) {
                // 处理嵌套的 expectedFrameRateRange
                const values = this.traversalLocals(field.getInitializer()[0]);
                if (values.length === 3) {
                    result.push(...values);
                }
            } else if (frameRateFields.includes(fieldName)) {
                const value = this.extractFieldValue(field, arkFile, arkMethod, stmt);
                if (value !== null && Number.isFinite(value) && value >= 0) {
                    result.push(value);
                }
            }
        }
        return result;
    }

    /**
     * 提取单个字段值
     */
    private extractFieldValue(field: ArkField, arkFile: ArkFile, arkMethod: ArkMethod, stmt: Stmt): number | null {
        const rightOp = this.getFieldRightOperand(field);
        return rightOp ? this.extractValueFromExpression(rightOp, arkFile, arkMethod, stmt) : null;
    }

    private getObjectFields(newExpr: ArkNewExpr, arkFile: ArkFile): ArkField[] | null {
        if (!(newExpr instanceof ArkNewExpr)) {
            return null;
        }
        const type = newExpr.getType();
        if (!(type instanceof ClassType)) {
            return null;
        }
        const arkClass = arkFile.getScene().getClass(type.getClassSignature());
        return arkClass?.getFields() || null;
    }

    /**
     * 从表达式中提取值
     */
    private extractValueFromExpression(value: Value, arkFile: ArkFile, arkMethod: ArkMethod, stmt: Stmt): number | null {
        if (value instanceof Constant) {
            return this.parseConstantValue(value.getValue());
        }
        if (value instanceof Local) {
            return this.resolveLocalValue(value, arkFile, arkMethod, stmt);
        }
        if (value instanceof ArkStaticFieldRef) {
            return this.resolveStaticFieldReference(value, arkFile);
        }
        if (value instanceof ArkInstanceFieldRef) {
            return this.resolveInstanceFieldReference(value, arkFile, arkMethod, stmt);
        }
        return null;
    }

    private parseConstantValue(constantValue: unknown): number | null {
        if (typeof constantValue === 'number') {
            return constantValue;
        }
        if (typeof constantValue === 'string') {
            const numValue = Number(constantValue);
            return !isNaN(numValue) && isFinite(numValue) ? numValue : null;
        }
        return null;
    }

    private resolveLocalValue(local: Local, arkFile: ArkFile, arkMethod: ArkMethod, stmt: Stmt): number | null {
        // 尝试 NumberUtils
        const numberValue = this.tryNumberUtils(arkFile, stmt, local);
        if (numberValue !== null) {
            return numberValue;
        }
        // 尝试使用 getFieldNum 处理文件级变量
        const fieldValues = this.getFieldNum(stmt, local, local.getName());
        if (fieldValues.length > 0) {
            return fieldValues[0];
        }
        // 追溯声明
        const declaringStmt = local.getDeclaringStmt();
        return (declaringStmt instanceof ArkAssignStmt) ?
            this.extractValueFromExpression(declaringStmt.getRightOp(), arkFile, arkMethod, stmt) : null;
    }

    private tryNumberUtils(arkFile: ArkFile, stmt: Stmt, value: Value): number | null {
        try {
            const scope = (stmt as StmtWithScope).scope;
            if (!scope) {
                return null;
            }
            const varInfo = new VarInfo(stmt, scope as ModelScope);
            const result = NumberUtils.getNumberByScope(arkFile, varInfo, value);
            return result && result.value !== 0 && Number.isFinite(result.value) ? result.value : null;
        } catch (e) {
            return null;
        }
    }

    /**
     * 解析静态字段引用
     */
    private resolveStaticFieldReference(staticFieldRef: ArkStaticFieldRef, arkFile: ArkFile): number | null {
        // 尝试 NumberUtils
        try {
            const numberValue = NumberUtils.getNumberByScope(arkFile, new VarInfo(null!, null!), staticFieldRef);
            if (numberValue && numberValue.value !== 0 && Number.isFinite(numberValue.value)) {
                return numberValue.value;
            }
        } catch (e) {
           
        }

        const fieldSignature = staticFieldRef.getFieldSignature();
        const declareSignature = fieldSignature.getDeclaringSignature();
        if (!(declareSignature instanceof ClassSignature)) {
            return null;
        }
        const declareClass = arkFile.getScene().getClass(declareSignature);
        const field = declareClass?.getStaticFieldWithName(staticFieldRef.getFieldName());
        return field ? this.extractComplexFieldValue(field, arkFile) : null;
    }

    /**
     * 解析实例字段引用
     */
    private resolveInstanceFieldReference(instanceFieldRef: ArkInstanceFieldRef, arkFile: ArkFile, arkMethod: ArkMethod, stmt: Stmt): number | null {
        const base = instanceFieldRef.getBase();
        const fieldName = instanceFieldRef.getFieldName();

        // 尝试使用 NumberUtils 解析
        const numberValue = this.tryNumberUtils(arkFile, stmt, instanceFieldRef);
        if (numberValue !== null && base instanceof Local) {
            // 尝试手动解析获取更准确的值
            const manualValue = this.resolveNestedFieldReference(base, fieldName, arkFile, arkMethod, stmt);
            // 如果手动解析成功且值不同，优先使用手动解析的值
            if (manualValue !== null && manualValue !== numberValue) {
                return manualValue;
            }
            return numberValue;
        }

        // NumberUtils 失败，使用嵌套字段解析
        return base instanceof Local ? this.resolveNestedFieldReference(base, fieldName, arkFile, arkMethod, stmt) : null;
    }

    /**
     * 解析嵌套字段引用（如 globalRange.expected, nest.a.b）
     */
    private resolveNestedFieldReference(base: Local, fieldName: string, arkFile: ArkFile, arkMethod: ArkMethod, stmt: Stmt): number | null {
        // 首先尝试通过作用域查找基础对象定义
        const baseValue = this.findVariableDefinitionInScope(base.getName(), arkFile, arkMethod, stmt);
        if (baseValue && 'isConstantValue' in baseValue && baseValue.isConstantValue) {
            return baseValue.value;
        }
        if (baseValue) {
            return this.extractNestedFieldValue(baseValue, fieldName, arkFile);
        }
        // 尝试使用 traversalLocals 方法处理复杂的嵌套引用
        const declaringStmt = base.getDeclaringStmt();
        if (declaringStmt) {
            const values = this.traversalLocals(declaringStmt);
            if (values.length > 0) {
                return values[0];
            }
        }

        // 对于复杂的嵌套引用，尝试在编译器生成的类中查找
        const compiledValue = this.findVariableInCompiledClasses(arkFile, base.getName(), fieldName);
        if (compiledValue !== null) {
            return compiledValue;
        }
        // 从声明语句获取右操作数
        if (!(declaringStmt instanceof ArkAssignStmt)) {
            return null;
        }
        const rightOp = declaringStmt.getRightOp();
        if (rightOp instanceof ArkNewExpr) {
            return this.extractNestedFieldValue(rightOp, fieldName, arkFile);
        }
        if (rightOp instanceof ArkInstanceFieldRef) {
            return this.resolveChainedFieldReference(rightOp, fieldName, arkFile, arkMethod, stmt);
        }

        return null;
    }

    /**
     * 提取嵌套字段值（专门处理 nest.a.b 这样的情况）
     */
    private extractNestedFieldValue(objectValue: Value | { isConstantValue: boolean; value: number } | null,
         targetFieldName: string, arkFile: ArkFile): number | null {
        if (objectValue && 'isConstantValue' in objectValue && objectValue.isConstantValue) {
            return objectValue.value;
        }
        if (!(objectValue instanceof ArkNewExpr)) {
            return null;
        }
        // 直接使用 getObjectFields 来获取对象字面量的字段
        const fields = this.getObjectFields(objectValue, arkFile);
        if (!fields) {
            return null;
        }
        // 递归查找目标字段
        for (const field of fields) {
            const fieldName = field.getName();
            const rightOp = this.getFieldRightOperand(field);

            if (fieldName === targetFieldName) {
                // 直接匹配的字段
                if (rightOp instanceof Constant) {
                    const value = rightOp.getValue();
                    return typeof value === 'number' ? value : null;
                }
            } else if (rightOp instanceof ArkNewExpr) {
                // 嵌套对象，递归查找目标字段
                const nestedValue = this.extractNestedFieldValue(rightOp, targetFieldName, arkFile);
                if (nestedValue !== null) {
                    return nestedValue;
                }
            }
        }
        return null;
    }

    /**
     * 在作用域中查找变量定义
     */
    private findVariableDefinitionInScope(variableName: string, arkFile: ArkFile, arkMethod: ArkMethod,
         stmt: Stmt): Value | { isConstantValue: boolean; value: number } | null {
        // 编译器生成的变量需要追溯到原始定义
        if (variableName.startsWith('%')) {
            return this.traceCompilerGeneratedVariable(variableName, arkFile, arkMethod);
        }

        // 在作用域中查找变量定义
        const scope = (stmt as StmtWithScope).scope;
        if (scope?.defList) {
            for (const varDef of scope.defList) {
                if (varDef.getName() === variableName && varDef.defStmt instanceof ArkAssignStmt) {
                    return varDef.defStmt.getRightOp();
                }
            }
        }

        // 在文件级别查找变量定义（如 const nest = {...}）
        const fileResult = this.findFileVariableDefinition(variableName, arkFile);
        if (fileResult) {
            return fileResult;
        }
        // 对于复杂的文件级常量（如 nest），使用 traversalImport 方法
        const importResult = this.traversalImport(arkFile, variableName);
        if (importResult.length > 0) {
            return { isConstantValue: true, value: importResult[0] };
        }

        // 尝试 traversalDefaultClass
        const defaultResult = this.traversalDefaultClass(arkFile, variableName);
        if (defaultResult.length > 0) {
            return { isConstantValue: true, value: defaultResult[0] };
        }

        // 对于复杂的文件级常量，尝试在编译器生成的类中查找
        const compiledValue = this.findVariableInCompiledClasses(arkFile, variableName);
        if (compiledValue !== null) {
            return { isConstantValue: true, value: compiledValue };
        }

        return null;
    }

    /**
     * 在编译器生成的类中查找复杂变量的值
     *
     * 基于类型信息和AST结构动态分析
     *
     * @param arkFile 当前文件
     * @param variableName 变量名
     * @param targetFieldName 目标字段名，可选
     * @returns 找到的数值，如果未找到则返回 null
     */
    private findVariableInCompiledClasses(arkFile: ArkFile, variableName: string, targetFieldName?: string): number | null {
        // 首先尝试找到原始变量的类型定义
        const variableType = this.findVariableTypeDefinition(arkFile, variableName);
        if (variableType) {
            return this.extractValueFromTypeDefinition(variableType, targetFieldName, arkFile);
        }

        // 如果找不到类型定义，回退到基于结构的分析
        return this.findValueByStructuralAnalysis(arkFile, variableName, targetFieldName);
    }

    /**
     * 基于结构分析查找值
     */
    private findValueByStructuralAnalysis(arkFile: ArkFile, variableName: string, targetFieldName?: string): number | null {
        for (const arkClass of arkFile.getClasses()) {
            const result = this.searchInRelatedClass(arkClass, variableName, targetFieldName);
            if (result !== null) {
                return result;
            }
        }
        return null;
    }

    /**
     * 在相关类中搜索值
     */
    private searchInRelatedClass(arkClass: ArkClass, variableName: string, targetFieldName?: string): number | null {
        const className = arkClass.getName();
        if (!this.isClassRelatedToVariable(className, variableName)) {
            return null;
        }
        for (const field of arkClass.getFields()) {
            const result = this.checkFieldForTargetValue(field, targetFieldName);
            if (result !== null) {
                return result;
            }
        }
        return null;
    }

    /**
     * 检查字段是否包含目标值
     */
    private checkFieldForTargetValue(field: ArkField, targetFieldName?: string): number | null {
        const fieldName = field.getName();
        const frameRateFields = ['expected', 'min', 'max'];

        // 精确匹配目标字段名
        if (targetFieldName && fieldName === targetFieldName) {
            return this.getValidThresholdValue(field);
        }

        // 只检查帧率相关字段
        if (!targetFieldName && frameRateFields.includes(fieldName)) {
            return this.getValidThresholdValue(field);
        }

        return null;
    }

    /**
     * 获取有效的阈值
     */
    private getValidThresholdValue(field: ArkField): number | null {
        const value = this.extractNumericValue(field);
        return (value !== null && value >= HIGH_FRAME_RATE_THRESHOLD) ? value : null;
    }

    /**
     * 判断类是否与变量相关
     */
    private isClassRelatedToVariable(className: string, variableName: string): boolean {
        // 编译器生成的类通常包含原始变量名的信息
        return className.includes(variableName) ||
            className.includes('%AC') ||
            className.includes('%dflt') ||
            className.includes('%instInit');
    }

    /**
     * 提取字段的数值
     */
    private extractNumericValue(field: ArkField): number | null {
        const rightOp = this.getFieldRightOperand(field);
        if (rightOp instanceof Constant) {
            return this.parseConstantValue(rightOp.getValue());
        }
        return null;
    }



    /**
     * 查找变量的类型定义
     */
    private findVariableTypeDefinition(arkFile: ArkFile, variableName: string): ClassType | null {
        for (const arkClass of arkFile.getClasses()) {
            const result = this.searchVariableInClass(arkClass, variableName);
            if (result) {
                return result;
            }
        }
        return null;
    }

    /**
     * 在类中搜索变量定义
     */
    private searchVariableInClass(arkClass: ArkClass, variableName: string): ClassType | null {
        for (const field of arkClass.getFields()) {
            const result = this.extractTypeFromMatchingField(field, variableName);
            if (result) {
                return result;
            }
        }
        return null;
    }

    /**
     * 从匹配的字段中提取类型
     */
    private extractTypeFromMatchingField(field: ArkField, variableName: string): ClassType | null {
        if (field.getName() !== variableName) {
            return null;
        }
        const rightOp = this.getFieldRightOperand(field);
        if (!(rightOp instanceof ArkNewExpr)) {
            return null;
        }
        const type = rightOp.getType();
        return type instanceof ClassType ? type : null;
    }

    /**
     * 从类型定义中提取值
     */
    private extractValueFromTypeDefinition(classType: ClassType, targetFieldName: string | undefined, arkFile: ArkFile): number | null {
        const arkClass = arkFile.getScene().getClass(classType.getClassSignature());
        if (!arkClass) {
            return null;
        }
        return this.searchFieldsRecursively(arkClass, targetFieldName, arkFile, new Set());
    }

    /**
     * 递归搜索字段，避免循环引用
     */
    private searchFieldsRecursively(arkClass: ArkClass, targetFieldName: string | undefined, arkFile: ArkFile, visited: Set<string>): number | null {
        const className = arkClass.getName();
        if (visited.has(className)) {
            return null;
        }
        visited.add(className);

        for (const field of arkClass.getFields()) {
            const fieldName = field.getName();

            // 如果指定了目标字段名，精确匹配
            if (targetFieldName && fieldName === targetFieldName) {
                const value = this.extractNumericValue(field);
                if (value !== null && value >= HIGH_FRAME_RATE_THRESHOLD) {
                    return value;
                }
            }

            // 如果没有指定目标字段名，检查所有数值字段
            if (!targetFieldName) {
                const value = this.extractNumericValue(field);
                if (value !== null && value >= HIGH_FRAME_RATE_THRESHOLD) {
                    return value;
                }
            }

            // 递归检查嵌套对象
            const nestedValue = this.searchNestedFields(field, targetFieldName, arkFile, visited);
            if (nestedValue !== null) {
                return nestedValue;
            }
        }

        return null;
    }

    /**
     * 搜索嵌套字段
     */
    private searchNestedFields(field: ArkField, targetFieldName: string | undefined, arkFile: ArkFile, visited: Set<string>): number | null {
        const rightOp = this.getFieldRightOperand(field);
        if (!(rightOp instanceof ArkNewExpr)) {
            return null;
        }
        const type = rightOp.getType();
        if (!(type instanceof ClassType)) {
            return null;
        }
        const nestedClass = arkFile.getScene().getClass(type.getClassSignature());
        return nestedClass ? this.searchFieldsRecursively(nestedClass, targetFieldName, arkFile, visited) : null;
    }



    /**
     * 在文件级别查找变量定义
     */
    private findFileVariableDefinition(variableName: string, arkFile: ArkFile): Value | null {
        // 首先检查默认类中的字段
        const defaultClassResult = this.searchVariableInDefaultClass(arkFile, variableName);
        if (defaultClassResult) {
            return defaultClassResult;
        }
        // 然后检查所有其他类
        return this.searchVariableInAllClasses(arkFile, variableName);
    }

    /**
     * 在默认类中搜索变量
     */
    private searchVariableInDefaultClass(arkFile: ArkFile, variableName: string): Value | null {
        const defaultClass = arkFile.getDefaultClass();
        if (!defaultClass) {
            return null;
        }

        return this.findFieldByNameInClass(defaultClass, variableName);
    }

    /**
     * 在所有类中搜索变量
     */
    private searchVariableInAllClasses(arkFile: ArkFile, variableName: string): Value | null {
        for (const arkClass of arkFile.getClasses()) {
            const result = this.findFieldByNameInClass(arkClass, variableName);
            if (result) {
                return result;
            }
        }
        return null;
    }

    /**
     * 在类中按名称查找字段
     */
    private findFieldByNameInClass(arkClass: ArkClass, variableName: string): Value | null {
        for (const field of arkClass.getFields()) {
            if (field.getName() === variableName) {
                return this.getFieldRightOperand(field);
            }
        }
        return null;
    }

    /**
     * 追溯编译器生成的变量到原始定义
     */
    private traceCompilerGeneratedVariable(_variableName: string, arkFile: ArkFile, arkMethod: ArkMethod): Value | null {
        // 在类字段中查找原始变量
        for (const field of arkMethod.getDeclaringArkClass().getFields()) {
            if (this.isLikelyOriginalVariable(field, arkFile)) {
                const result = this.getFieldRightOperand(field);
                if (result) {
                    return result;
                }
            }
        }
        return null;
    }

    private getFieldRightOperand(field: ArkField): Value | null {
        const initializers = field.getInitializer();
        if (initializers.length === 0) {
            return null;
        }
        const lastInitializer = initializers[initializers.length - 1];
        return lastInitializer instanceof ArkAssignStmt ? lastInitializer.getRightOp() : null;
    }



    /**
     * 检查字段是否可能是文件级别的变量
     */
    private isFileVariableName(field: ArkField): boolean {
        try {
            // 1. 检查字段的声明位置和作用域
            if (!this.isFieldDeclaredAtFileLevel(field)) {
                return false;
            }

            // 2. 检查字段的修饰符和属性
            if (!this.isUserDefinedField(field)) {
                return false;
            }

            // 3. 检查字段的初始化方式
            if (!this.hasValidVariableInitialization(field)) {
                return false;
            }

            return true;
        } catch (error) {
            // 如果 IR 分析失败，回退到基本的名称检查
            return this.isValidUserDefinedName(field.getName());
        }
    }

    /**
     * 检查字段是否在文件级别声明
     */
    private isFieldDeclaredAtFileLevel(field: ArkField): boolean {
        try {
            const declaringClass = field.getDeclaringArkClass();
            if (!declaringClass) {
                return false;
            }
            const className = declaringClass.getName();

            // 默认类通常表示文件级别的声明
            if (className === DEFAULT_ARK_CLASS_NAME) {
                return true;
            }
            // 检查是否为顶级类
            return this.isTopLevelClass(declaringClass, className);
        } catch (error) {
            return true; 
        }
    }

    /**
     * 检查是否为顶级类
     */
    private isTopLevelClass(declaringClass: ArkClass, className: string): boolean {
        // 通过 IR 信息检查
        const arkFile = declaringClass.getDeclaringArkFile();
        if (arkFile) {
            const topLevelClasses = arkFile.getClasses();
            if (topLevelClasses.includes(declaringClass)) {
                return true;
            }
        }

        // 排除明显的嵌套类和编译器生成的类
        return !className.includes('$') && !className.includes('%');
    }

    /**
     * 检查字段是否为用户定义的字段
     */
    private isUserDefinedField(field: ArkField): boolean {
        const fieldName = field.getName();

        // 检查字段名称特征
        if (this.isCompilerGeneratedFieldName(fieldName)) {
            return false;
        }
        // 检查字段的声明来源
        return this.isFieldInUserDefinedClass(field);
    }

    /**
     * 检查是否为编译器生成的字段名
     */
    private isCompilerGeneratedFieldName(fieldName: string): boolean {
        return fieldName.startsWith('$') ||
               fieldName.startsWith('%') ||
               fieldName.includes('$$') ||
               /^_\d+$/.test(fieldName);
    }

    /**
     * 检查字段是否在用户定义的类中
     */
    private isFieldInUserDefinedClass(field: ArkField): boolean {
        try {
            const declaringClass = field.getDeclaringArkClass();
            if (!declaringClass) {
                return true;
            }
            const className = declaringClass.getName();
            return !className.includes('%') && !className.includes('$$');
        } catch (error) {
            return true; // 保守策略
        }
    }

    /**
     * 检查字段是否有有效的变量初始化
     */
    private hasValidVariableInitialization(field: ArkField): boolean {
        try {
            const initializers = field.getInitializer();
            if (!initializers || initializers.length === 0) {
                return true;
            }
            const firstInitializer = initializers[0];
            return this.isValidInitializationStatement(firstInitializer);
        } catch (error) {
            return true; // 保守策略
        }
    }

    /**
     * 检查是否为有效的初始化语句
     */
    private isValidInitializationStatement(initializer: Stmt): boolean {
        if (!(initializer instanceof ArkAssignStmt)) {
            return true;
        }
        const rightOp = initializer.getRightOp();
        return this.isValidInitializationOperand(rightOp);
    }

    /**
     * 检查是否为有效的初始化操作数
     */
    private isValidInitializationOperand(rightOp: Value): boolean {
        // 常量初始化
        if (rightOp instanceof Constant) {
            return true;
        }
        // 对象字面量初始化
        if (rightOp instanceof ArkNewExpr) {
            return this.isValidObjectLiteralInitialization(rightOp);
        }

        // 变量引用初始化
        if (rightOp instanceof Local) {
            return true;
        }
        // 字段引用初始化
        if (rightOp instanceof ArkInstanceFieldRef || rightOp instanceof ArkStaticFieldRef) {
            return true;
        }

        return true; // 其他类型也认为是有效的
    }

    /**
     * 检查对象字面量初始化是否有效
     */
    private isValidObjectLiteralInitialization(newExpr: ArkNewExpr): boolean {
        try {
            // 检查对象的类型信息
            const type = newExpr.getType();
            if (type instanceof ClassType) {
                const classSignature = type.getClassSignature();
                // 排除明显的编译器生成的类型
                return !classSignature.toString().includes('%') &&
                    !classSignature.toString().includes('$$');
            }
            return true;
        } catch (error) {
            return true;
        }
    }

    /**
     * 基本的用户定义名称检查
     */
    private isValidUserDefinedName(name: string): boolean {
        // 基本的标识符规范检查
        if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
            return false;
        }

        // 排除明显的系统标识符
        const systemIdentifiers = [
            'constructor', 'prototype', '__proto__', 'toString', 'valueOf'
        ];

        return !systemIdentifiers.includes(name) &&
            !name.startsWith('__') &&
            !name.startsWith('%');
    }

    /**
     * 检查字段是否可能是原始变量
     */
    private isLikelyOriginalVariable(field: ArkField, arkFile: ArkFile): boolean {
        if (!this.isFileVariableName(field)) {
            return false;
        }
        const rightOp = this.getFieldRightOperand(field);
        if (!(rightOp instanceof ArkNewExpr)) {
            return false;
        }
        const fields = this.getObjectFields(rightOp, arkFile);
        return !!(fields && fields.length > 0);
    }
    /**
     * 解析链式字段引用
     */
    private resolveChainedFieldReference(fieldRef: ArkInstanceFieldRef, _targetFieldName: string, 
        arkFile: ArkFile, arkMethod: ArkMethod, stmt: Stmt): number | null {
        const baseValue = this.resolveInstanceFieldReference(fieldRef, arkFile, arkMethod, stmt);
        if (baseValue !== null) {
            return baseValue;
        }
        const fieldSignature = fieldRef.getFieldSignature();
        const declareSignature = fieldSignature.getDeclaringSignature();
        if (!(declareSignature instanceof ClassSignature)) {
            return null;
        }
        const declareClass = arkFile.getScene().getClass(declareSignature);
        const field = declareClass?.getField(fieldSignature);
        return field ? this.extractComplexFieldValue(field, arkFile) : null;
    }

    /**
     * 从字段引用中提取值
     */
    private extractFromFieldRef(_stmt: Stmt, fieldRef: ArkInstanceFieldRef | ArkStaticFieldRef, arkMethod: ArkMethod): number[] {
        const arkFile = arkMethod.getDeclaringArkFile();
        return fieldRef instanceof ArkStaticFieldRef ?
            this.extractFromStaticFieldRef(fieldRef, arkFile) :
            this.extractFromInstanceFieldRef(fieldRef, arkFile);
    }

    /**
     * 从静态字段引用中提取值
     */
    private extractFromStaticFieldRef(fieldRef: ArkStaticFieldRef, arkFile: ArkFile): number[] {
        const fieldSignature = fieldRef.getFieldSignature();
        const declareSignature = fieldSignature.getDeclaringSignature();
        if (!(declareSignature instanceof ClassSignature)) {
            return [];
        }
        const declareClass = arkFile.getScene().getClass(declareSignature);
        const field = declareClass?.getStaticFieldWithName(fieldRef.getFieldName());
        if (!field) {
            return [];
        }
        const value = this.extractComplexFieldValue(field, arkFile);
        return value !== null && value >= HIGH_FRAME_RATE_THRESHOLD ? [value] : [];
    }

    /**
     * 从实例字段引用中提取值
     */
    private extractFromInstanceFieldRef(fieldRef: ArkInstanceFieldRef, arkFile: ArkFile): number[] {
        const fieldSignature = fieldRef.getFieldSignature();
        const declareSignature = fieldSignature.getDeclaringSignature();
        if (!(declareSignature instanceof ClassSignature)) {
            return [];
        }
        const declareClass = arkFile.getScene().getClass(declareSignature);
        const field = declareClass?.getField(fieldSignature);
        if (!field) {
            return [];
        }
        const value = this.extractComplexFieldValue(field, arkFile);
        return value !== null && value >= HIGH_FRAME_RATE_THRESHOLD ? [value] : [];
    }

    /**
     * 提取复杂字段值，支持嵌套引用
     */
    private extractComplexFieldValue(field: ArkField, arkFile: ArkFile): number | null {
        const rightOp = this.getFieldRightOperand(field);
        if (!rightOp) {
            return null;
        }

        // 常量值
        if (rightOp instanceof Constant) {
            return this.parseConstantValue(rightOp.getValue());
        }

        // 静态字段引用
        if (rightOp instanceof ArkStaticFieldRef) {
            return this.extractFromStaticFieldReference(rightOp, arkFile);
        }

        // 实例字段引用
        if (rightOp instanceof ArkInstanceFieldRef) {
            return this.extractFromInstanceFieldReference(rightOp, arkFile);
        }

        return null;
    }

    /**
     * 从静态字段引用中提取值
     */
    private extractFromStaticFieldReference(rightOp: ArkStaticFieldRef, arkFile: ArkFile): number | null {
        const fieldSignature = rightOp.getFieldSignature();
        const declareSignature = fieldSignature.getDeclaringSignature();
        if (!(declareSignature instanceof ClassSignature)) {
            return null;
        }
        const declareClass = arkFile.getScene().getClass(declareSignature);
        const staticField = declareClass?.getStaticFieldWithName(rightOp.getFieldName());
        return staticField ? this.extractComplexFieldValue(staticField, arkFile) : null;
    }

    /**
     * 从实例字段引用中提取值
     */
    private extractFromInstanceFieldReference(rightOp: ArkInstanceFieldRef, arkFile: ArkFile): number | null {
        const base = rightOp.getBase();
        if (!(base instanceof Local)) {
            return null;
        }
        const declaringStmt = base.getDeclaringStmt();
        if (!(declaringStmt instanceof ArkAssignStmt)) {
            return null;
        }
        const rightOpOfStmt = declaringStmt.getRightOp();
        if (!(rightOpOfStmt instanceof ArkNewExpr)) {
            return null;
        }
        return this.findFieldInObjectFields(rightOpOfStmt, rightOp.getFieldName(), arkFile);
    }

    /**
     * 在对象字段中查找指定字段
     */
    private findFieldInObjectFields(newExpr: ArkNewExpr, fieldName: string, arkFile: ArkFile): number | null {
        const fields = this.getObjectFields(newExpr, arkFile);
        const targetField = fields?.find(f => f.getName() === fieldName);
        return targetField ? this.extractComplexFieldValue(targetField, arkFile) : null;
    }

    private getFieldNum(stmt: Stmt, arg: Local, name: string, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile();

        // 尝试局部变量
        const declaringStmt = arg.getDeclaringStmt();
        if (declaringStmt) {
            const localValues = this.traversalLocals(declaringStmt, depth);
            if (localValues.length > 0 && localValues.every(v => Number.isFinite(v) && v >= 0)) {
                return localValues;
            }
        }

        // 尝试全局变量
        const globalValues = this.traversalDefaultClass(arkFile, name, depth);
        if (globalValues.length > 0 && globalValues.every(v => Number.isFinite(v) && v >= 0)) {
            return globalValues;
        }

        // 尝试导入模块
        const importValues = this.traversalImport(arkFile, name, depth);
        return (importValues.length > 0 && importValues.every(v => Number.isFinite(v) && v >= 0)) ? importValues : [];
    }

    private traversalImport(arkFile: ArkFile, name: string, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        for (const subImport of arkFile.getImportInfos()) {
            if (subImport.getImportClauseName() !== name) {
                continue;
            }
            const importArkFile = subImport.getLazyExportInfo()?.getDeclaringArkFile();
            if (!importArkFile) {
                return this.traversaModuleFile(arkFile, subImport, depth);
            }

            // 尝试默认类
            const defaultValues = this.traversalDefaultClass(importArkFile, name, depth);
            if (defaultValues.length > 0) {
                return defaultValues;
            }
            // 尝试导出信息
            const exportValues = this.processExportInfos(importArkFile, name, depth);
            if (exportValues.length > 0) {
                return exportValues;
            }
            return this.traversaModuleFile(arkFile, subImport, depth);
        }
        return [];
    }

    private processExportInfos(importArkFile: ArkFile, name: string, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        for (const exportInfo of importArkFile.getExportInfos()) {
            if (exportInfo.getExportClauseName() !== name) {
                continue;
            }
            const arkExport = exportInfo.getArkExport();
            if (arkExport instanceof Local) {
                const result = this.processExportLocal(arkExport, depth);
                if (result.length > 0) {
                    return result;
                }
            }
        }
        return [];
    }

    private processExportLocal(arkExport: Local, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        const stmt = arkExport.getDeclaringStmt();
        if (!(stmt instanceof ArkAssignStmt) || !(stmt.getRightOp() instanceof Local)) {
            return [];
        }
        const type = stmt.getRightOp().getType();
        if (!(type instanceof ClassType)) {
            return [];
        }
        const arkFile = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile();
        const fields = arkFile?.getClass(type.getClassSignature())?.getFields();
        return fields ? this.getReasonableFieldValues(fields, depth) : [];
    }

    private traversaModuleFile(arkFile: ArkFile, subImport: ImportInfo, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        const from = subImport.getFrom() ?? '';
        const moduleScene = arkFile?.getScene().getModuleScene(from);
        if (!moduleScene) {
            return [];
        }
        for (const moduleFile of moduleScene.getModuleFilesMap().values()) {
            const result = this.searchInModuleFile(moduleFile, subImport, depth);
            if (result.length > 0) {
                return result;
            }
        }
        return [];
    }

    /**
     * 在模块文件中搜索值
     */
    private searchInModuleFile(moduleFile: ArkFile, subImport: ImportInfo, depth: number): number[] {
        // 首先尝试默认类
        const defValues = this.traversalDefaultClass(moduleFile, subImport.getImportClauseName(), depth);
        if (defValues.length > 0) {
            return defValues;
        }
        // 然后检查所有类的字段
        return this.searchInAllClassFields(moduleFile, depth);
    }

    /**
     * 在所有类的字段中搜索
     */
    private searchInAllClassFields(moduleFile: ArkFile, depth: number): number[] {
        for (const arkClass of moduleFile.getClasses()) {
            const result = this.searchInClassFields(arkClass, depth);
            if (result.length > 0) {
                return result;
            }
        }
        return [];
    }

    /**
     * 在类的字段中搜索
     */
    private searchInClassFields(arkClass: ArkClass, depth: number): number[] {
        for (const field of arkClass.getFields()) {
            const values = this.traversalLocals(field.getInitializer()[0], depth);
            if (values.length > 0) {
                return values;
            }
        }
        return [];
    }

    private traversalLocals(declaringStmt: Stmt, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH || !(declaringStmt instanceof ArkAssignStmt)) {
            return [];
        }
        const method = declaringStmt.getCfg().getDeclaringMethod();
        const rightOp = declaringStmt.getRightOp();

        if (rightOp instanceof Local || rightOp instanceof ArkNewExpr) {
            const type = rightOp.getType();
            if (type instanceof ClassType) {
                const arkClass = method.getDeclaringArkFile().getScene().getClass(type.getClassSignature());
                const fields = arkClass?.getFields();
                return fields ? this.getReasonableFieldValues(fields, depth) : [];
            }
        }
        if (rightOp instanceof ArkInstanceFieldRef) {
            const field = method.getDeclaringArkClass().getField(rightOp.getFieldSignature());
            return field ? this.traversalLocals(field.getInitializer()[0], depth + 1) :
                this.traversalImport(method.getDeclaringArkFile(), rightOp.getBase().getName(), depth + 1);
        }
        if (rightOp instanceof ArkStaticFieldRef) {
            return this.processStaticFieldRef(rightOp, method, depth);
        }
        return [];
    }

    private processStaticFieldRef(rightOp: ArkStaticFieldRef, method: ArkMethod, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        const fieldSignature = rightOp.getFieldSignature();
        const declareSignature = fieldSignature.getDeclaringSignature();
        if (!(declareSignature instanceof ClassSignature)) {
            return [];
        }
        const declareClass = method.getDeclaringArkFile().getScene().getClass(declareSignature);
        const field = declareClass?.getStaticFieldWithName(rightOp.getFieldName());
        return field ? this.traversalLocals(field.getInitializer()[0], depth + 1) : [];
    }

    private traversalDefaultClass(arkFile: ArkFile, name: string, depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        // 检查默认类的方法中的局部变量
        const defaultClassResult = this.searchInDefaultClassMethods(arkFile, name, depth);
        if (defaultClassResult.length > 0) {
            return defaultClassResult;
        }
        // 检查所有类的字段
        return this.searchInAllClassFieldsByName(arkFile, name, depth);
    }

    /**
     * 在默认类的方法中搜索局部变量
     */
    private searchInDefaultClassMethods(arkFile: ArkFile, name: string, depth: number): number[] {
        const defaultClass = arkFile.getDefaultClass();
        for (const method of defaultClass.getMethods()) {
            const result = this.searchInMethodLocals(method, name, depth);
            if (result.length > 0) {
                return result;
            }
        }
        return [];
    }

    /**
     * 在方法的局部变量中搜索
     */
    private searchInMethodLocals(method: ArkMethod, name: string, depth: number): number[] {
        const locals = method.getBody()?.getLocals();
        if (!locals) {
            return [];
        }
        for (const [key, value] of locals) {
            if (this.isMatchingLocal(value, key, name)) {
                const result = this.traversalLocals(value.getDeclaringStmt()!, depth + 1);
                if (result.length > 0) {
                    return result;
                }
            }
        }
        return [];
    }

    /**
     * 检查是否为匹配的局部变量
     */
    private isMatchingLocal(value: Local, key: string, name: string): boolean {
        return value instanceof Local && key === name && !!value.getDeclaringStmt();
    }

    /**
     * 在所有类的字段中按名称搜索
     */
    private searchInAllClassFieldsByName(arkFile: ArkFile, name: string, depth: number): number[] {
        for (const arkClass of arkFile.getClasses()) {
            const result = this.searchInClassFieldsByName(arkClass, name, depth);
            if (result.length > 0) {
                return result;
            }
        }
        return [];
    }

    /**
     * 在类的字段中按名称搜索
     */
    private searchInClassFieldsByName(arkClass: ArkClass, name: string, depth: number): number[] {
        for (const field of arkClass.getFields()) {
            if (field.getName() === name) {
                const result = this.traversalLocals(field.getInitializer()[0], depth + 1);
                if (result.length > 0) {
                    return result;
                }
            }
        }
        return [];
    }

    private getReasonableFieldValues(fields: ArkField[], depth: number = 0): number[] {
        if (depth > MAX_RECURSION_DEPTH) {
            return [];
        }
        const fieldValues: { [key: string]: number } = {};
        const frameRateFields = this.getFrameRateFields(fields);

        for (const field of fields) {
            const fieldName = field.getName();

            // 特殊处理 expectedFrameRateRange 字段
            if (fieldName === SPECIAL_FIELD_NAME) {
                return this.traversalLocals(field.getInitializer()[0], depth + 1);
            }

            // 处理帧率相关字段
            if (frameRateFields.includes(fieldName)) {
                const value = this.processFieldValue(field, depth);
                if (value !== null) {
                    fieldValues[fieldName] = value;
                }
            }
        }

        // 检查是否所有帧率字段都 >= 阈值
        const allFieldsValid = frameRateFields.length > 0 && frameRateFields.every(name =>
            fieldValues[name] !== undefined && fieldValues[name] >= HIGH_FRAME_RATE_THRESHOLD
        );

        return allFieldsValid ? frameRateFields.map(name => fieldValues[name]) : [];
    }

    private processFieldValue(field: ArkField, depth: number = 0): number | null {
        if (depth > MAX_RECURSION_DEPTH) {
            return null;
        }
        const initializer = field.getInitializer()[0];
        if (!(initializer instanceof ArkAssignStmt)) {
            return null;
        }
        const arkFile = field.getDeclaringArkClass().getDeclaringArkFile();
        const scope = CheckerStorage.getInstance().getScope(arkFile.getFilePath());
        if (!scope) {
            return null;
        }
        const varInfo = new VarInfo(initializer, scope);
        const reDefValue = NumberUtils.getNumberByScope(arkFile, varInfo, initializer.getRightOp());

        if (reDefValue.type === 0) {
            return reDefValue.value;
        }
        // 递归处理子作用域
        for (const childScope of scope.childScopeList) {
            const childVarInfo = new VarInfo(initializer, childScope);
            const childResult = NumberUtils.getNumberByScope(arkFile, childVarInfo, initializer.getRightOp());
            if (childResult.type === 0) {
                return childResult.value;
            }
        }
        return null;
    }

    public reportIssue(arkFile: ArkFile, stmt: Stmt, methodName: string): void {
        const text = stmt.getOriginalText();
        if (!text || text.length === 0) {
            return;
        }
        const severity = this.rule.alert ?? this.metaData.severity;
        const originPos = stmt.getOriginPositionInfo();
        const methodIndex = text.lastIndexOf(methodName);
        const startColumn = originPos.getColNo() + (methodIndex >= 0 ? methodIndex : 0);

        const defects = new Defects(
            originPos.getLineNo(),
            startColumn,
            startColumn + methodName.length,
            this.metaData.description,
            severity,
            this.rule.ruleId,
            arkFile.getFilePath(),
            this.metaData.ruleDocPath,
            true,
            false,
            false
        );

        this.issues.push(new IssueReport(defects, undefined));
    }

    private isSupportedFile(filePath: string): boolean {
        return filePath.toLowerCase().endsWith('.ets') || filePath.toLowerCase().endsWith('.ts') || filePath.toLowerCase().endsWith('.js');
    }

}